package com.lingjtx.common.security.limit;

import com.alibaba.fastjson2.JSON;
import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.ResponseCode;
import com.lingjtx.common.core.ResponseResult;
import com.lingjtx.common.core.constant.SignatureType;
import com.lingjtx.common.core.util.SignatureHelper;
import com.lingjtx.common.core.annotation.ApiSignature;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class ApiSignatureState extends HandlerState<ProceedingJoinPoint, HttpServletRequest> {

    private String info;

    public String getInfo() {
        return info;
    }

    public void setInfo(String info) {
        this.info = info;
    }

    @Override
    public ResponseResult<Object> retError() {
        return ResponseResult.createByError(ResponseCode.NOT_SIGN.getCode(), this.getInfo());
    }

    @Override
    public void handler(ProceedingJoinPoint point, HttpServletRequest request, RedisOptions redis) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        ApiSignature annotation = signature.getMethod().getAnnotation(ApiSignature.class);
        if (Objects.nonNull(annotation)) {
            String signStr = request.getHeader("Signature");
            Object[] args = point.getArgs();

            String body = "";
            if (Objects.nonNull(args) && args.length > 0) {
                body = JSON.toJSONString(args[0]);
            }
            SignatureType type = SignatureHelper.verify(signStr, body, redis);
            if (SignatureType.SUCCESS.equals(type)) {
                return;
            }
            super.setErrorState(true);
            this.setInfo(type.toString());
        }
    }
}
